import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Dropdown, Form, Input, Select, Space, Tag, Modal, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useAccess, Access } from 'umi';
import { request } from 'umi';
import EditCom from './edit';
import UserScopeMap from './userScopeMap';
import MessageCom from './message';
import WorkExtendCom from './workExtend';

const { Option } = Select;
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

type businessReportItem = {
  id: string;
  url: string | undefined;
  reportName: string;
};

export default (props: any) => {
  const requestsUrls = {
    list: '/sys/account/list',
    delete: '/sys/account/delete',
  };
  const actionRef = useRef<ActionType>();
  const editRef = useRef();
  const workExtendRef = useRef();
  const messageRef = useRef();
  const UserScopeMapRef = useRef();
  const access = useAccess();
  const [form] = Form.useForm(); //搜索表单
  const pageAuth = access[props.route.key];
  // const pageAuth = access['222222'] || {};
  const [companyIdvalueEnum, setcompanyIdvalueEnum] = useState({});

  const getOrgList = () => {
    request('/sys/account/findOfficeTreeList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      console.log(res);
      const obj = {};
      const orglist = res?.data || [];
      orglist.map((e: any, i: number) => {
        obj[e.id] = {
          text: e.name,
        };
      });
      setcompanyIdvalueEnum(obj);
    });
    //
  };
  useEffect(() => {
    getOrgList();
  }, []);

  const resetPwd = (id: any) => {
    Modal.confirm({
      title: '确认重置密码?',
      content: '',
      onOk() {
        console.log('OK');

        request('/sys/account/savePassword', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            id,
          },
        }).then(() => {
          message.info('密码重置成功');
          actionRef.current?.reload();
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const deleteFn = (id) => {
    Modal.confirm({
      title: '确认删除？',
      content: '',
      onOk() {
        console.log('OK');

        request(requestsUrls.delete, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            id,
          },
        }).then(() => {
          actionRef.current?.reload();
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const columns: ProColumns<businessReportItem>[] = [
    {
      title: '归属公司',
      align: 'center',
      key: 'companyId',
      dataIndex: 'companyId',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: companyIdvalueEnum,
    },
    {
      title: '公司名称',
      align: 'center',
      key: 'companyName',
      dataIndex: 'companyName',
      hideInSearch: true,
    },
    {
      title: '登录名',
      align: 'center',
      key: 'account',
      dataIndex: 'account',
      //hideInSearch: true,
    },
    {
      title: '用户名称',
      align: 'center',
      key: 'name',
      dataIndex: 'name',
      //hideInSearch: true,
    },
    {
      title: '是否允许登录',
      align: 'center',
      key: 'enable',
      dataIndex: 'enable',
      hideInSearch: true,
      render: (txt) => {
        return txt == '1' ? '启用' : '禁用';
      },
    },

    {
      title: '手机电话',
      align: 'center',
      key: 'phone',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '电子邮箱',
      align: 'center',
      key: 'email',
      dataIndex: 'email',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            editRef.current?.init(record.id, record);
          }}
        >
          编辑
        </a>,
        <a
          key="deleteable"
          onClick={() => {
            deleteFn(record.id);
          }}
        >
          删除
        </a>,
        <a
          key="resetPwd"
          onClick={() => {
            resetPwd(record.id);
          }}
        >
          重置密码
        </a>,
        <a
          key="resetPwd"
          onClick={() => {
            messageRef.current.init(record.id);
          }}
        >
          消息发送方式
        </a>,
        <a
          key="editable"
          onClick={() => {
            workExtendRef.current?.init(record.id, record);
          }}
        >
          工作继任
        </a>,

        <a
          key="editable"
          onClick={() => {
            UserScopeMapRef.current?.init(record.id);
          }}
        >
          用户分配
        </a>,

      ],
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        columns={columns}
        // search={false}
        rowKey="id"
        params={form.getFieldsValue()}
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: T & {
            pageSize: number;
            current: number;
          },
          sort,
          filter,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          console.log(params, sort, filter);
          const response: any = await request(requestsUrls.list, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            data: {
              ...params,
              ...{
                pageNo: params.current,
                pageSize: params.pageSize,
              },
            },
          });
          return {
            data: response?.data?.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: response?.data?.totalCount,
          };
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              editRef.current?.init();
            }}
            type="primary"
          >
            新建
          </Button>,
        ]}
      />

      <EditCom
        ref={editRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />
      <MessageCom
        ref={messageRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />
      <WorkExtendCom
        ref={workExtendRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />
      <UserScopeMap
        ref={UserScopeMapRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />



    </>
  );
};
